// pages/index/index_order.js
var App = getApp();
let orderMoney = 0; //订单初始需要支付的价格
let boxId = '';
var commitOrder = true;
var needPayMoney=0;//订单最后需要结算的金额
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userIsVip: false, //当前用户是不是vip
    orderMsg: [], //要提交的订单信息
    orginPrice: 0, //商品总价
    discountPrice: '0.00', //优惠价格
    totalNum: 0,
    address: '',
    hasDiscount: true,//有可用优惠券
    accountMoney: '0.00',
    youhui: [], //优惠券列表
    youhuiPrice: '0.00', //优惠券减免
    vipMsg: {  //vip信息
      money: '5.00',
      msg: '首月5元，之后15元/月'
    },
    openVip: false, //开通vip
    vipDiscount: '0.00', //vip减免
    lastPayMoney: '0.00', //实际支付价格
    yueSwicth:false,
    discountMsg:'', //优惠券减免信息
    realPay:'0.00'// 订单实际支付的金额
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.removeStorageSync('coupon');//清空缓存的优惠券信息
    wx.removeStorageSync('discountIndex');//清空缓存的优惠券信息
    wx.showLoading({
      title: '加载中',
    })
    let list = JSON.parse(options.ordermsg);
    let num = 0;
    let is_vip = wx.getStorageSync('allUserMsg').vip.is_vip;//判断用户身份
    for (let i = 0; i < list.length; i++) {
      num += list[i].buy_num
    }
    
    orderMoney = parseFloat(options.total);
    boxId = options.boxId;
    this.setData({
      userIsVip: is_vip,
      orginPrice: parseFloat(options.origin).toFixed(2), //商品总价
      lastPayMoney: orderMoney.toFixed(2),
      orderMsg: list,
      totalNum: num,
      discountPrice: parseFloat(options.activeSave).toFixed(2), //优惠价格
      vipDiscount: parseFloat(options.vipSave).toFixed(2), //优惠券减免
    })
    this.getBoxAddress();
    this.getDiscountInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let coupon = this.data.youhui;
    let index = wx.getStorageSync('discountIndex');
    if (index != '' && index > -1) {
      this.setData({
        youhuiPrice: coupon[index].scheme,
        discountMsg: '满' + coupon[index].rule + '减' +coupon[index].scheme
      })
    } else {
      this.setData({
        youhuiPrice: 0
      })
    }
    this.computeRealMoney();//计算价格
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
   
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  //获取宿舍地址
  getBoxAddress: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/login/getaddress', //接口地址
      data: {
        token: wx.getStorageSync('token'),
        box_id: boxId,
      },
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        if (res.data.error == 0) {
          that.setData({
            address: res.data.data.address
          })
          wx.hideLoading();
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },

  //vip开关
  vipSwitch: function () {
    this.setData({
      openVip: !this.data.openVip,
      hasDiscount: false,//有可用优惠券
      youhuiPrice: '0.00', //优惠券减免
    })
    this.computeRealMoney();//计算价格

    wx.removeStorageSync('discountIndex');//重新获取优惠信息
    this.getDiscountInfo(); 
  },


  //去商品详情页
  goGoodsDetail: function () {
    wx.navigateTo({
      url: '/pages/index/mall/mall_order_goods?goods=' + JSON.stringify(this.data.orderMsg) + '&isVip=' + this.data.openVip
    })
  },

  //余额开关
  userYueSwitch: function () {
    if (this.data.accountMoney == 0) {
      return false;
    }
    this.setData({
      yueSwicth: !this.data.yueSwicth
    })
    this.computeRealMoney();//计算价格
  },

  //获取优惠信息
  getDiscountInfo: function () {
    let that = this;
    let goodsList = that.data.orderMsg;
    for (var i = 0; i < goodsList.length; i++) {//更新购买商品数量
      goodsList[i].number = goodsList[i].buy_num;
    }
    wx.request({
      url: App.data.globalAPI + '/order/users/getinfo',
      data: {
        box_id: boxId,
        goods: goodsList,
        token: wx.getStorageSync('token'),
        buy_vip: that.data.openVip ? 1:0
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        const arr = res.data;
        if (arr.error == 0) {
          // let vipPrice = 'vipMsg.money'
          that.setData({
            accountMoney: arr.data.money,
            // [vipPrice]: parseFloat(arr.data.vip_price).toFixed(2)
          })
          if(arr.data.vip_price!='-1'){
            that.setData({
              vipMsg:{
                money: arr.data.vip_price,
                msg: '现在开通 ' + arr.data.vip_price + '元/月'
              }
            })
          }
          if (arr.data.coupon.length > 0) {
            that.setData({
              hasDiscount: true,//有可用优惠券
              youhui: arr.data.coupon,
            })
          } else {
            that.setData({
              hasDiscount: false,//无可用优惠券
            })
          }
          if (that.data.accountMoney>0){
            that.setData({
              yueSwicth:true
            })
            that.computeRealMoney();
          }

        } else {
          wx.showToast({
            title: arr.msg,
            icon: 'none',
            duration: 800
          })
        }
      }, fail(res) {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      }
    })
  },

  //计算实际支付金额
  computeRealMoney: function () {
    let vip_discount = parseFloat(this.data.vipDiscount); //优惠券折扣
    let vip_price = parseFloat(this.data.vipMsg.money); //vip价格
    let realMoney = parseFloat(orderMoney);
    //选择了优惠券
    if (this.data.youhuiPrice > 0) {
      if (parseFloat(this.data.youhuiPrice) > parseFloat(realMoney)) {
        realMoney = 0
      } else {
        realMoney = parseFloat(realMoney - this.data.youhuiPrice)
      }
    }
    //开通了vip
    if (this.data.openVip) {
      realMoney = parseFloat(realMoney + vip_price - vip_discount)
    } 

    needPayMoney = parseFloat(realMoney).toFixed(2); //未使用余额前先记录需要支付的订单金额

    if (this.data.yueSwicth) {//使用余额
      if (parseFloat(this.data.accountMoney) > parseFloat(realMoney)) { //账户余额大于订单金额
        realMoney = 0
      } else {
        realMoney = parseFloat(realMoney - this.data.accountMoney)
      }
    }
    this.setData({
      realPay: needPayMoney,
      lastPayMoney: parseFloat(realMoney).toFixed(2)
    })
  },

  // 选择优惠券
  onChoseDiscout: function () {
    wx.navigateTo({
      url: '../goods_mall/choseDiscount',
    })
  },

  // 确认支付
  onPaymentHandle: function () {
    let that = this;
    let payWay = '';
    let goodsList = that.data.orderMsg;
    let useYue = 0;//使用的余额
    let cpIndex = wx.getStorageSync('discountIndex');//使用第几张优惠券
    if (that.data.payChecked && that.data.accountMoney > 0 && that.data.lastPayMoney == 0) {
      payWay = 'account';
    } else if (that.data.payChecked && that.data.accountMoney > 0 && that.data.lastPayMoney > 0) {
      payWay = 'mixed';
    } else if (that.data.lastPayMoney == 0) {
      payWay = 'account';
    } else {
      payWay = 'online';
    }
    for (var i = 0; i < goodsList.length; i++) {//更新购买商品数量
      goodsList[i].number = goodsList[i].buy_num;
    }
    
    if (that.data.yueSwicth) {//使用余额
      if (needPayMoney - that.data.accountMoney > 0) {
        useYue = parseFloat(that.data.accountMoney).toFixed(2);
      } else {
        useYue = parseFloat(needPayMoney).toFixed(2);
      }
    }

    let cpId = '';
    if (cpIndex != '' && cpIndex > -1) {
      cpId = that.data.youhui[cpIndex].id;
    }


    if (!commitOrder) {
      wx.showToast({
        title: '请勿频繁操作',
        icon: 'none'
      })
      return false;
    }

    wx.request({
      url: App.data.globalAPI + '/order/users/pay',
      data: {
        token: wx.getStorageSync('token'),
        pay_type: payWay,//在线支付: online 余额支付: account 混合支付: mixed,
        pay_method: payWay == 'account' ? 'account' : 'wxlite',
        coupon_id: cpId,
        pay: parseFloat(needPayMoney).toFixed(2), //实付款
        box_id: boxId,
        account_pay: useYue,//余额支付金额 
        online_pay: that.data.lastPayMoney,//在线支付金额 
        goods: JSON.stringify(goodsList),
        client_type: 'wxlite',
        buy_vip: that.data.openVip?1:0
      }, 
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          commitOrder = false;
          var payArr = res.data.data.pay;
          var orderArr = res.data.data.order;
          if (payWay == 'account') {
            var curPageArr = getCurrentPages();
            var page = curPageArr[curPageArr.length - 2];
            page.clearShopCart();//清空购物车
            page.getBoxGoodsList();//获取消费列表
            commitOrder = true;
            if (that.data.openVip){ //开通了vip更新用户信息
              page.getTokenLogin()
            }
            // 更新本地的上次消费记录
            if (boxId != wx.getStorageSync('allUserMsg').last_order.box_id){
              let usermsg = wx.getStorageSync('allUserMsg');
              usermsg.last_order.box_id = boxId;
              wx.setStorageSync('allUserMsg', usermsg);
            }
            wx.redirectTo({
              url: '/pages/index/replenishment/pay_result?order_id=' + orderArr.order_id + '&order_no=' + orderArr.order_no + '&price=' + orderArr.pay + '&jifen=' + orderArr.integral,
            })
            return false;
          }
          wx.requestPayment({
            timeStamp: payArr.timeStamp,
            nonceStr: payArr.nonceStr,
            package: payArr.package,
            signType: payArr.signType,
            paySign: payArr.paySign,
            success(res) {
              var curPageArr = getCurrentPages();
              var page = curPageArr[curPageArr.length - 2]; 
              page.clearShopCart();//清空购物车
              page.getBoxGoodsList();//获取消费列表
              commitOrder = true;
              if (that.data.openVip) { //开通了vip更新用户信息
                page.getTokenLogin()
              }

              if (boxId != wx.getStorageSync('allUserMsg').last_order.box_id) {
                let usermsg = wx.getStorageSync('allUserMsg');
                usermsg.last_order.box_id = boxId;
                wx.setStorageSync('allUserMsg', usermsg);
              }

              wx.redirectTo({
                url: '/pages/index/replenishment/pay_result?order_id=' + orderArr.order_id + '&order_no=' + orderArr.order_no + '&price=' + orderArr.pay + '&jifen=' + orderArr.integral
              })
            },
            fail(res) {
              setTimeout(function () {
                commitOrder = true;
              }, 6000)
            }
          })
        }
        else {
          commitOrder = true;
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }

      }, fail(res) {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      }
    })
  },

  // 选择优惠券
  goChoseDiscount:function(){
    if(this.data.youhui.length>0){
      wx.navigateTo({
        url: 'index_order_quan?list=' + JSON.stringify(this.data.youhui),
      })
    }
  },
})